<template>
  <div
    ref="constrainTable"
    class="v-property-constaint g-relative"
  >
    <div class="_table-body">
      <div class="g-relative g-pd-l-10">
        <div class="g-flex _table-row g-ov-hidden _table-title">
          <div
            class="g-flex-0 _cell _name-column g-one-line"
            :style="{ width: nameColumnWidth + 'px' }"
          >
            {{ $t("名称") }}
          </div>
          <div class="g-flex-1 _cell _value-column">
            <span class="g-m-l-8">{{ $t("约束规范") }}</span>
          </div>
        </div>
        <!-- 列表展示 -->
        <div v-if="constraintData && constraintData.length > 0">
          <div
            v-for="(row, index) of constraintData"
            :key="index"
            class="g-flex _table-row g-ov-hidden"
            :class="{ '_current-row': row.modelId === curRowId }"
            @click="handleCilckRow(row)"
          >
            <div
              v-show="row.modelId === curRowId"
              class="_table-body-icon"
            >
              <img
                src="statics/icons/app/arrowchoose.svg"
                class="g-m-r-4"
              />
            </div>
            <div
              class="g-flex-0 _cell _name-column g-one-line"
              :style="{ width: nameColumnWidth + 'px' }"
            >
              <!-- 列表新增 -->
              <span>
                <span>
                  <el-input
                    ref="nameEdit"
                    v-model="row.nameForEdit"
                    class="_name-edit"
                    @blur="handleBlur(row)"
                    @keyup.enter="handleBlur(row)"
                  ></el-input>
                </span>
              </span>
            </div>
            <div class="g-flex-1 _cell _value-column">
              <TMValueSpecification
                v-if="row.metaClass === MetaclassType.DurationConstraint"
                :row="row.valueSpecificationRow"
              ></TMValueSpecification>
              <MValueSpecification
                v-else
                :selected="true"
                :row="row.valueSpecificationRow"
              ></MValueSpecification>
            </div>
          </div>
        </div>
        <div v-if="!constraintData || constraintData.length == 0">
          <NoData></NoData>
        </div>
        <span
          class="_movebar _vertical g-block"
          :style="{ left: nameColumnWidth + 12 + 'px' }"
          @mousedown="handleMouseDownVertical"
        ></span>
      </div>
    </div>
    <div class="g-footer-button g-pd-l-10">
      <MDropdown>
        <MButton
          type="add"
          text="新建"
          :disabled="isModelDisabled"
        />
        <template #dropdown>
          <MDropdownMenuItem
            v-for="(item, index) in operationList"
            :key="index"
            @click="handleNewClick(item)"
          >
            {{ $t(item.label) }}
          </MDropdownMenuItem>
        </template>
      </MDropdown>
      <MButton
        type="use"
        text="应用"
        :disabled="isModelDisabled"
        @click="handleApply"
      />
      <MButton
        type="disuse"
        text="弃用"
        :disabled="!currentRow || isModelDisabled"
        @click="handleDelete"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, watch, inject, ref, Ref } from "vue";
import { ConstraintData, DeletePropertyDto, SelectedRelation } from "./types";

import { modelService } from "@/modules/model/service";
import MValueSpecification from "../attribute/propertyEditors/common/ValueSpecification.vue";
import TMValueSpecification from "../attribute/propertyEditors/common/TimeValueSpecification.vue";
import { MetaclassType } from "@/constants/MetaclassType";
import NoData from "./noData.vue";
import MDropdown from "@/common/dropdown/Dropdown.vue";
import MDropdownMenuItem from "@/common/dropdown/DropdownMenuItem.vue";
import MButton from "@/common/button/Button.vue";

const props = defineProps<{
  constraintData: ConstraintData[];
  modelId?: string;
}>();

const specificationEdit = ref();
const constraintsPaneModel = app.activeProject!.attributeTabsModel.constraintsPaneModel;
const curRowId = ref<string | undefined>();
const currentRow = computed(() => {
  return constraintsPaneModel.tableData.find(it => it.modelId === curRowId.value);
});
const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

const operationList = [
  { label: "约束", constrainType: 0 },
  { label: "时间段约束", constrainType: 1 },
  { label: "安全约束", constrainType: 0, appliedStereotypes: ["UAF::Security::Constraints::SecurityConstraint"] }
];
// const addRowValue = ref<any>(
//   {
//     // constraintName: constraintsPaneModel.newConstraintName,
//     constraintId: '',
//     specificationId: '',
//     addMethod: '',
//     dataType: PropertyDataType.STRING,
//     readonly: false,
//     key: 'Constraint-specification',
//     modelId: props.modelId!,
//     value: '',
//     isSelected: true,
//     valueSpecificationInfo: {
//       metaclass: MetaclassType.OpaqueExpression,
//       element: { id: '', metaclass: MetaclassType.OpaqueExpression, icon: '', name: '' },
//       value: '',
//       elementId: '',
//       extraValue: '',

//     }
//   }
// );

// const showDropDown = computed(() => {
//   return constraintsPaneModel.tabsModel.data.modelData?.baseSt?.startsWith("UAF::Personnel::Taxonomy");
// });

const nameColumnWidth = ref<number>(110);
let mouseStartX = 0;
let originWidth = 0;
const minWidth = 20;

// const deleteItem = ref<ConstraintData>();

// const isAddNewConstrain = ref(false);

watch(
  () => props.constraintData,
  () => {
    if (app.$route.query.highlightModelId) {
      curRowId.value = app.$route.query.highlightModelId as string;
      constraintsPaneModel.tableData.forEach((x, y) => {
        if (x.modelId === curRowId.value) {
          specificationEdit.value[y].$refs.valueEdit.focus();
        }
      });
    }
  }
);

const handleNewClick = async (item: SelectedRelation) => {
  await constraintsPaneModel.handleCreateConstraint(item);
};

async function handleBlur(row: ConstraintData) {
  if (row.constraintName == row.nameForEdit) return;

  await constraintsPaneModel.handleRename(row);
}
async function handleApply() {
  await constraintsPaneModel.handleApply();
}
async function handleDelete() {
  if (!currentRow.value) {
    return;
  }
  const dto: DeletePropertyDto = {
    projectId: app.activeProject!.config.id,
    deleteInstanceId: currentRow.value.constraintId,
    deleteMethod: "",
    instanceId: props.modelId!,
    key: "Element-constraints"
  };
  await modelService.removePropertyValue(dto);

  await constraintsPaneModel.fresh();
}

function handleCilckRow(row: ConstraintData) {
  console.log("property---", row);
  curRowId.value = row.constraintId;
  console.log(curRowId);
}
function handleMouseDownVertical(event: any) {
  mouseStartX = event.clientX;
  originWidth = nameColumnWidth.value;
  window.addEventListener("mousemove", handleMouseMoveVertical);
  window.addEventListener("mouseup", handleMouseUpVertical);
}

function handleMouseMoveVertical(event: any) {
  const maxWidth = app.global.isIpcWindow ? 300 : app.global.siderWidth - 40;
  const mouseEndX = event.clientX;
  let changeWidth = mouseEndX - mouseStartX;
  let width = originWidth + changeWidth;
  if (width > maxWidth) {
    width = maxWidth;
  } else if (width < minWidth) {
    width = minWidth;
  }
  nameColumnWidth.value = width;
}

function handleMouseUpVertical() {
  window.removeEventListener("mousemove", handleMouseMoveVertical);
  window.removeEventListener("mouseup", handleMouseUpVertical);
}
</script>
<style lang="scss">
@import "@/assets/css/theme.scss";
.v-property-constaint {
  height: 100%;
  overflow: hidden;

  display: flex;
  ._table-body-icon {
    position: absolute;
    left: 1px;
    margin-top: 4px;
  }
  flex-direction: column;
  ._table-title {
    background: $titlebar-bg-color;
  }
  ._table-body {
    overflow: auto;
    margin-bottom: 16px;
  }
  ._active-row {
    background-color: $nth-of-type-bg-color !important;
  }
  ._editor-height {
    min-height: 48px;
    width: 30px;
    border-left: 1px solid rgb(221, 221, 221);
  }
  ._string-editor {
    min-height: 72px;
  }
  ._instance-bg {
    background-color: white;
  }

  ._cell {
    border-top: 1px solid #ddd;
    border-left: 1px solid #ddd;
    box-sizing: border-box;
    font-size: 12px;
    line-height: 26px;
  }
  ._slot-parent {
    background: #ecf0f7;
  }
  ._constrain_no-data {
    height: 350px;
    border: 1px solid red;
  }
  ._name-column {
    padding: 0 8px;
  }
  ._value-column {
    padding: 0;
    line-height: 26px;
    position: relative;
    border-right: 1px solid #ddd;

    ._slot-values {
      display: inline-flex;
      margin-right: 40px;
    }
    ._slot-add {
      display: inline-flex;
      position: absolute;
      right: 0;
      top: 0;
      width: 40px;
      height: 100%;
      ._add-img {
        position: absolute;
        right: 8px;
        top: 6px;
      }
    }
  }
  ._current-row {
    ._cell {
      box-shadow: inset -1px 0px 0px 0px #e0e0e0, inset 0px -1px 0px 0px #e0e0e0;
      border-top-color: $theme-color;
      border-left-color: $theme-color;
    }

    ._name-column {
      padding: 0 8px;

      color: white;
    }
    ._value-column {
      box-sizing: border-box;
      line-height: 24px;
      border-right-color: $theme-color;
    }
  }
  ._current-row + ._table-row {
    line-height: 26px;
    ._cell {
      border-top-color: $theme-color;
    }
  }
  ._icons {
    width: 30px;
    border: 1px solid red;
  }
  ._table-row:last-of-type {
    ._cell {
      border-bottom: 1px solid #ddd;
    }
  }
  ._table-row._current-row:last-of-type {
    ._cell {
      border-bottom: 1px solid $theme-color;
    }
  }

  .el-input__inner {
    border: none;
    box-sizing: border-box;
    height: 24px;
    line-height: 24px;
    background: none;
    box-shadow: none;
    text-align: left;
  }
  .el-textarea__inner:focus {
    background: none;
    box-shadow: none;
  }
  .el-textarea__inner {
    background: none;
    box-shadow: none;
    padding: 5px 8px;
    border: none;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .el-input-border {
    border: none;
  }
  ._disabled {
    // color: #979797;
    cursor: not-allowed;
  }

  ._movebar {
    position: absolute;
    &._vertical {
      cursor: col-resize;
      width: 8px;
      height: 100%;
      top: 0;
    }
  }
}
</style>
